#!/usr/bin/python
# -*- coding:utf-8 -*-
import datetime
import imp
import locale
from optparse import OptionParser
import sys
import urllib2
import GetWallpaperLog

CONSOLE_ENCODE = locale.getpreferredencoding()
logger = GetWallpaperLog.logging.getLogger("getwallpaper")

parser = OptionParser(usage="""usage: %prog [ --proxy http://hogehoge:port ] [options] target-url
get data from target-url and put to file.
default output filename is YYYYMMDDHHMM.jpg""")
parser.add_option("-p", "--proxy", dest="proxy", default=None,
                  help="URL http://hogehoge:port", metavar="URL")
parser.add_option("-d", "--dst", dest="dst", default=None,
                  help="dst FOLDER", metavar="FOLDER")
parser.add_option("", "--hour", action="store_true", dest="hour", default=None,
                  help="hour only.")
parser.add_option("", "--prefix", dest="prefix", default="",
                  help="specify output file PREFIX.", metavar="PREFIX")
parser.add_option("-e", "--ext", dest="ext", default=".jpg",
                  help="specify output file EXT.", metavar="EXT")
parser.add_option("-f", "--file", dest="outfile", default=None,
                  help="specify output FILENAME. This option use then, ignore --dst, --prefix and --ext", metavar="FILENAME")
parser.add_option("", "--url-plugin",
                  dest="urlPlugin",
                  help="image url plugin")

(options, args) = parser.parse_args()

if options.proxy :
    proxy = {'http':options.proxy}
    proxy_handler = urllib2.ProxyHandler(proxy)
    opener = urllib2.build_opener(proxy_handler)
else :
    opener = urllib2.build_opener()

if len(args) < 1 :
    sys.stderr.write("require a url\n")
    sys.exit(1)

sourceUrl = args[0]

if options.urlPlugin :
    try :
        pluginInfo = imp.find_module(options.urlPlugin)
    except ImportError, e:
        sys.stderr.write((u"invalid url plugin name %s : %s\n"%(options.urlPlugin, e)).encode(CONSOLE_ENCODE))
        sys.exit(1)
    try :
        plugin = imp.load_module(options.urlPlugin, pluginInfo[0], pluginInfo[1], pluginInfo[2])
        imageUrl = plugin.getImageUrl(sourceUrl, logger, options.proxy)
    finally :
        pluginInfo[0].close()
else :
    imageUrl = sourceUrl

try :
    urllib2.install_opener(opener)
    request = urllib2.Request(imageUrl)
    response = opener.open(request)
except Exception, e :
    sys.stddrr.write(e)
    sys.exit(1)

try :
    d = datetime.datetime.today()

    if options.outfile :
        fileName = options.outfile
    elif options.hour :
        fileName = "%s%02d%s"%(options.prefix, d.hour, options.ext)
        if options.dst :
            fileName = options.dst + fileName
    else :
        fileName = "%s%04d%02d%02d%02d%02d%s"%(options.prefix, d.year, d.month, d.day, d.hour, d.minute, options.ext)
        if options.dst :
            fileName = options.dst + fileName

    outFile = open(fileName, "wb")
    outFile.write(response.read())
    outFile.close()
except Exception, f:
    sys.stderr.write(f)
    sys.exit(1)
